﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Storm.TextEditor.Editor
{
	/// <summary>
	/// Represents a Form that can design a TextStyle.
	/// </summary>
	public partial class TextStyleDesignerDialog
		: Form
	{
		#region Fields

		private TextStyle style     = null;
		private TextStyle tempStyle = null;

		#region Events

		/// <summary>
		/// Occurs when the TextStyle that the TextStyleDesignerDialog has changed.
		/// </summary>
		public event EventHandler Change;

		#endregion

		#endregion

		#region Methods

		#region Private

		/// <summary>
		/// Previews the selected TextStyle in the style previewer.
		/// </summary>
		private void PreviewStyle()
		{
			TextStyle textStyle = tempStyle;

			lblPreview.ForeColor = textStyle.ForeColor;
			if (textStyle.BackColor != Color.Transparent)
				lblPreview.BackColor = textStyle.BackColor;
			else
				lblPreview.BackColor = Color.White;

			FontStyle fontStyle = FontStyle.Regular;

			if (textStyle.Bold)
				fontStyle |= FontStyle.Bold;

			if (textStyle.Italic)
				fontStyle |= FontStyle.Italic;

			if (textStyle.Underline)
				fontStyle |= FontStyle.Underline;

			lblPreview.Font = new Font("Courier New", 11f, fontStyle);
		}

		#endregion

		#region Protected

		/// <summary>
		/// Raises the Change event.
		/// </summary>
		protected virtual void OnChange()
		{
			if (this.Change != null)
				this.Change(this, EventArgs.Empty);
		}

		#endregion

		#region EventHandlers

		private void OnStyleGridPropertyValueChanged(object s, PropertyValueChangedEventArgs e)
		{
			this.PreviewStyle();
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			style.BackColor = tempStyle.BackColor;
			style.ForeColor = tempStyle.ForeColor;

			style.Bold      = tempStyle.Bold;
			style.Italic    = tempStyle.Italic;
			style.Underline = tempStyle.Underline;

			this.OnChange();
			this.DialogResult = DialogResult.OK;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
		}

		#endregion

		#endregion

		/// <summary>
		/// Initializes a new instance of TextStyleDesignerDialog.
		/// </summary>
		public TextStyleDesignerDialog(TextStyle style)
		{
			InitializeComponent();

			this.style = style;
			this.tempStyle = style.Clone() as TextStyle;

			styleGrid.SelectedObject = tempStyle;
			lblCaption.Text = style.ToString();

			this.PreviewStyle();
		}
	}
}
